import { useRef, useLayoutEffect } from "react"
import Session from "../Session"
// import * as echarts from "echarts"
import "echarts-gl"
import { parseData } from "../../utils"
import * as am4core from "@amcharts/amcharts4/core"
import * as am4charts from "@amcharts/amcharts4/charts"

import am4themes_kelly from "@amcharts/amcharts4/themes/kelly"

am4core.useTheme(am4themes_kelly)

// const option = (data = [], colors = [], labels) => ({
//   legend: {
//     orient: "vertical",
//     left: "bottom"
//   },
//   color: colors,
//   xAxis3D: { type: "value" },
//   yAxis3D: { type: "value" },
//   zAxis3D: { type: "value" },
//   grid3D: {
//     viewControl: { autoRotate: true }
//   },
//   series: [
//     {
//       name: "Access From",
//       type: "pie",
//       radius: "50%",
//       height: 30, // 设置高度实现3D立体感
//       data: data.map((item, index) => ({ value: item, name: labels[index] })),
//       itemStyle: { borderRadius: 5 }
//       // emphasis: {
//       //   itemStyle: {
//       //     shadowBlur: 10,
//       //     shadowOffsetX: 0,
//       //     shadowColor: 'rgba(0, 0, 0, 0.5)'
//       //   }
//       // },
//       // viewControl: {  // 3D视图控制
//       //   distance: 150,  // 视角距离
//       //   alpha: 40,     // 上下旋转角度
//       //   beta: 35,      // 左右旋转角度
//       //   autoRotate: true,  // 自动旋转
//       //   autoRotateSpeed: 10  // 旋转速度
//       // }
//     }
//   ]
// })

const AuditSituation = ({ chartData = {}, className }) => {
  const overviewChart = useRef(null)
  const issueChart = useRef(null)

  const { auditOverviewChart, riskTrendsChart } = chartData
  const issues = parseData(riskTrendsChart)
  const overview = parseData(auditOverviewChart)
  console.log("overview", overview)
  console.log("issues", issues)

  // 提取foundIssue和rectification到组件级别，使其在整个组件中可用
  const {
    empty,
    inProgress,
    completed,
    foundIssue = {},
    rectification = {}
  } = issues

  // 
  const createOverviewChart = () => {
    const chart = am4core.create("overview", am4charts.PieChart3D)
    overviewChart.current = chart
    chart.hiddenState.properties.opacity = 0 // this creates initial fade-in

    // chart.legend = new am4charts.Legend();

    const { data = [], labels = [] } = overview
    const colors = [
      "#63b2ee",
      "#76da91",
      "#f8cb7f",
      "#f89588",
      "#7cd6cf",
      "#9192ab",
      "#7898e1",
      "#efa666",
      "#eddd86",
      "#9987ce",
      "#63b2ee",
      "#76da91"
    ]

    chart.data = data.map((item, index) => ({
      litres: item,
      country: labels[index]
    }))
    chart.angle = 60
    chart.depth = 10
    chart.fontSize = 12
    chart.tooltip.label.fontSize = 12
    chart.logo.disabled = true
    // chart.padding(40, 40, 40, 40);
    // console.log(chart, "am4core.color")

    // 绘图区域背景
    // chart.plotContainer.background.fill = am4core.color("#ffffff");
    // chart.plotContainer.background.fillOpacity = 0.8;

    const series = chart.series.push(new am4charts.PieSeries3D())
    series.dataFields.value = "litres"
    series.dataFields.category = "country"
    series.colors.list = colors.map((color) => am4core.color(color))

    series.ticks.template.stroke = am4core.color("#000000")
    series.ticks.template.strokeOpacity = 0.8

    // 使指示线颜色与对应饼块一致
    series.ticks.template.adapter.add("stroke", function (fill, target) {
      if (target.dataItem && target.dataItem.slice) {
        return target.dataItem.slice.fill
      }
      return fill
    })
    series.radius = am4core.percent(110)

    series.labels.template.html = `<div><div>{value}</div><div>{category}</div></div>`
    series.slices.template.states.getKey("active").properties.distance = 20 // 分离距离
    series.slices.template.states.getKey(
      "active"
    ).properties.shiftDistance = 1.6 // 3D高度变化
  }

  const createIssueChart = () => {
    const chart = am4core.create("issue", am4charts.PieChart3D)
    issueChart.current = chart
    chart.hiddenState.properties.opacity = 0 // this creates initial fade-in

    const colors = ["#76da91", "#63b2ee", "#f8cb7f"]
    // chart.legend = new am4charts.Legend();
    // console.log("issues", issues)
    // 这里不需要再次解构，因为我们已经在组件级别解构过了
    // const { foundIssue, rectification } = issues;

    chart.data = [
      {
        val: empty,
        name: "未整改"
      },
      {
        val: inProgress,
        name: "整改中"
      },
      {
        val: completed,
        name: "完成整改"
      }
    ]
    chart.angle = 60
    chart.depth = 10
    chart.fontSize = 12
    chart.tooltip.label.fontSize = 12
    chart.logo.disabled = true
    // chart.padding(40, 40, 40, 40);
    // console.log(chart, "am4core.color")

    // 绘图区域背景
    // chart.plotContainer.background.fill = am4core.color("#ffffff");
    // chart.plotContainer.background.fillOpacity = 0.8;

    const series = chart.series.push(new am4charts.PieSeries3D())
    series.dataFields.value = "val"
    series.dataFields.category = "name"
    series.colors.list = colors.map((color) => am4core.color(color))

    series.ticks.template.stroke = am4core.color("#000000")
    series.ticks.template.strokeOpacity = 0.8

    // 使指示线颜色与对应饼块一致
    series.ticks.template.adapter.add("stroke", function (fill, target) {
      if (target.dataItem && target.dataItem.slice) {
        return target.dataItem.slice.fill
      }
      return fill
    })
    series.radius = am4core.percent(110)

    series.labels.template.html = `<div><div>{value}</div><div>{category}</div></div>`
    series.slices.template.states.getKey("active").properties.distance = 20 // 分离距离
    series.slices.template.states.getKey(
      "active"
    ).properties.shiftDistance = 1.6 // 3D高度变化
  }

  useLayoutEffect(() => {
    createOverviewChart()
    createIssueChart()

    return () => {
      if (overviewChart.current) {
        overviewChart.current.dispose()
      }

      if (issueChart.current) {
        issueChart.current.dispose()
      }
    }
  }, [])
  // 审计总览
  // 使用后端返回的overviewData，如果不存在则使用默认值
  const overviewData = overview.overviewData || {
    // 比同类单位高或者低多少个百分点
    percent: 0,
    // 接受审计总次数
    count: 0
  }
  // 累计发现问题
  // 已经在第118行通过解构得到了foundIssue，这里不需要重新定义
  // const foundIssue = foundIssue

  // 整改问题
  // rectification也已经在第118行解构得到
  // const rectification = rectification

  return (
    <Session
      title="二、审计情况"
      className={className}
      style={{
        backgroundImage: `url('bottom_left.png')`,
        backgroundSize: "cover",
        backgrounRepeat: "no-repeat",
        height: "257px"
      }}
    >
      <div className="flex gap-4">
        <div className="flex-1">
          <h3 className="text-center font-bold mt-1">审计总览</h3>
          <div id="overview" className="w-full h-[120px]"></div>
          <div className="text-sm text-[#414141]">
            <p className="text-center mt-1">
              接受审计总次数{" "}
              <span className="text-[#EB7801] font-bold">
                {overviewData.count}次
              </span>
            </p>
            <p className="text-center mt-1">
              相对同类单位
              <span
                className={
                  overviewData.percent >= 0
                    ? "text-[#EB7801] font-bold"
                    : "text-[#01CD76] font-bold"
                }
              >
                {overviewData.percent >= 0 ? "高" : "低"}
                {Math.abs(overviewData.percent)}个百分点
              </span>
            </p>
          </div>
        </div>

        <div className="flex-1">
          <h3 className="text-center font-bold mt-1">发现问题</h3>
          <div id="issue" className="w-full h-[120px]"></div>
          <div className="text-sm text-[#414141]">
            <p className="text-center mt-1">
              累计发现问题:{" "}
              <span className="text-[#EB7801] font-bold">
                {foundIssue.count}项
              </span>
              ，相对同类单位
              <span
                className={
                  foundIssue.higher >= 0
                    ? "text-[#EB7801] font-bold"
                    : "text-[#01CD76] font-bold"
                }
              >
                {foundIssue.higher >= 0 ? "高" : "低"}
                {Math.abs(foundIssue.higher)}个百分点
              </span>
            </p>
            <p className="text-center mt-1">
              未整改问题:{" "}
              <span className="text-[#EB7801] font-bold">
                {rectification.count}项
              </span>
              ，相对同类单位
              <span
                className={
                  rectification.higher >= 0
                    ? "text-[#EB7801] font-bold"
                    : "text-[#01CD76] font-bold"
                }
              >
                {rectification.higher >= 0 ? "高" : "低"}
                {Math.abs(rectification.higher)}个百分点
              </span>
            </p>
          </div>
        </div>
      </div>
    </Session>
  )
}

export default AuditSituation
